/**
 *
 * @param tree  树数据
 * @param selectedKeys  选中的所有key
 * @return  返回所有选中的节点key
 */

interface TsTree {
	id: string;
	children: TsTree[];
}
export const findSelectedNodes = (tree: TsTree[], selectedKeys: Array<string | number>): Array<string | number> => {
	// 如果当前节点为根节点，并且所有子节点都被选中，则只返回根节点key
	if (selectedKeys.includes('0')) {
		return ['0'];
	}
	const selectedNodes = [];
	for (const node of tree) {
		const nodeKey = node.id;
		const children = node.children || [];

		// 判断当前节点是否被选中
		if (selectedKeys.includes(nodeKey)) {
			let allChildrenSelected = true;

			for (const child of children) {
				const childKey = child.id;
				if (!selectedKeys.includes(childKey)) {
					allChildrenSelected = false;
					break;
				}
			}
			// 如果所有子节点都被选中，则只返回父节点key
			if (allChildrenSelected) {
				selectedNodes.push(nodeKey);
			} else {
				// 否则将已选中的子节点key加入结果数组
				for (const child of children) {
					const childKey = child.id;
					if (selectedKeys.includes(childKey)) {
						selectedNodes.push(childKey);
					}
				}
			}
		} else {
			// 如果当前节点未选中，则继续递归查找其子节点
			const childNodes = findSelectedNodes(children, selectedKeys);
			if (childNodes.length) {
				selectedNodes.push(...childNodes);
			}
		}
	}

	return selectedNodes;
};

// ============联动设备及算法数据格式化 帮助后端处理 后续后端重构区域架构后会删除============
// 格式化处理数据联动级联框
export const formatCascader = (serviceForm: any, treeData: any): any => {
	const obj = JSON.parse(JSON.stringify(serviceForm));
	if (treeData && treeData.length && obj?.aiSrvExtraArgs?.algorithmLinkageAlarm === 1) {
		const treeId = obj.aiSrvExtraArgs.algorithmLinkageAlarmList[1];
		for (let index = 0; index < treeData.length; index++) {
			if (treeData[index].children) {
				const areaId = (treeData[index].children as any[]).find((item) => item.id === treeId)?.areaId;
				if (areaId) {
					obj.aiSrvExtraArgs.algorithmLinkageAlarmList.splice(1, 0, areaId);
					return obj;
				}
			}
		}
	} else {
		return obj;
	}
};

// 后端返回数据 前端预处理
export const handleCascaderData = (data: any): any => {
	const obj = data;
	const arr = obj.aiSrvExtraArgs.algorithmLinkageAlarmList;
	if (arr && arr.length) {
		obj.aiSrvExtraArgs.algorithmLinkageAlarmList.splice(1, 1);
	}
	return obj;
};

// ============联动设备及算法数据格式化 帮助后端处理 后续后端重构区域架构后会删除 END============
